from app.code import codeApi
from module.codes import Codes
from flask import request, make_response, jsonify, json
from utility.authorization import Authorization
from datetime import datetime

auth = Authorization()
_TIME_FORMAT = '%F %H:%M:%S'


@codeApi.route('/code', methods=['POST', 'GET', 'DELETE'])
def code():
    # 编译并存储历史记录
    if request.method == 'POST':
        # 获取代码
        data = request.get_json()
        codes = Codes(code=data['code'])
        # 解释python代码
        res = codes.interpret()
        return jsonify(res)
    else:
        token = request.headers['Authorization']
        if auth.vertify_token(token):
            codes = Codes()
            # 获取历史记录
            if request.method == 'GET':
                user_id = request.args.get("userId")
                list_data = codes.get_codes(user_id)
                for item in list_data:
                    item['code_result'] = json.loads(item['code_result'])
                    item['create_time'] = datetime.strftime(item['create_time'], _TIME_FORMAT)
                return jsonify(list_data)
            # 删除聊天记录
            if request.method == 'DELETE':
                data = request.get_json()
                if 'userId' in data:
                    if codes.clear_codes(data['userId']) > 0:
                        return jsonify('已清空所有历史记录')
                if 'codeId' in data:
                    if codes.delete_code(data['codeId']) == 1:
                        return jsonify('删除成功')
        else:
            return make_response('token失效', 403)


@codeApi.route('/judge_code', methods=['POST'])
def judge_code():
    token = request.headers['Authorization']
    if auth.vertify_token(token):
        if request.method == 'POST':
            # 获取代码
            codes = Codes()
            data = request.get_json()
            problem_id = data['problemId']
            result = codes.get_result(problem_id)
            complete_code = data['code'] + '''

if __name__ == '__main__':
    print(''' + result['function_name'] + '''(''' + result['problem_in'] + '''))
'''
            codes.code = complete_code
            user_id = data['userId']
            # 解释python代码
            res = codes.interpret()
            res['out'] = res['out'].replace('\r', '').replace('\n', '').replace('\t', '')
            # 存放历史记录
            codes.insert_code(json.dumps(res), user_id)
            codes.update_all_times(data['problemId'])
            if res['out'] == result['problem_result']:
                codes.update_ac_times(data['problemId'])
            res.update(result)
            return jsonify(res)
    else:
        return make_response('token失效', 403)
